import React, { useState } from 'react';
import { Card, Button, Space, Collapse, Empty, Spin, message, Tag } from 'antd';
import { 
  SettingOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  CopyOutlined,
  ArrowUpOutlined
} from '@ant-design/icons';
import { ParameterCategory, Parameter, Project } from '../../types';
import ParameterItem from './ParameterItem';
import ParameterForm from './ParameterForm';
import ParameterValueForm from './ParameterValueForm';

const { Panel } = Collapse;

interface CategoryCardProps {
  category: ParameterCategory;
  project?: Project | null;
  onEditCategory: (category: ParameterCategory) => void;
  onDeleteCategory: (category: ParameterCategory) => void;
  onPinToTop: (category: ParameterCategory) => Promise<void>;
  onAddParameter: (category: ParameterCategory) => void;
  onEditParameter: (category: ParameterCategory, parameter: Parameter) => void;
  onDeleteParameter: (category: ParameterCategory, parameter: Parameter) => void;
  onPinParameterToTop: (category: ParameterCategory, parameter: Parameter) => Promise<void>;
  onCreateParameter: (category: ParameterCategory, values: any) => Promise<void>;
  onUpdateParameter: (category: ParameterCategory, parameter: Parameter, values: any) => Promise<void>;
  onSetParameterValues: (category: ParameterCategory, parameter: Parameter, values: string[]) => Promise<void>;
  loading?: boolean;
}

const CategoryCard: React.FC<CategoryCardProps> = ({
  category,
  project,
  onEditCategory,
  onDeleteCategory,
  onPinToTop,
  onAddParameter,
  onEditParameter,
  onDeleteParameter,
  onPinParameterToTop,
  onCreateParameter,
  onUpdateParameter,
  onSetParameterValues,
  loading = false
}) => {
  const [expanded, setExpanded] = useState(false);
  const [parameterFormVisible, setParameterFormVisible] = useState(false);
  const [editingParameter, setEditingParameter] = useState<Parameter | undefined>();
  const [parameterValueFormVisible, setParameterValueFormVisible] = useState(false);
  const [selectedParameter, setSelectedParameter] = useState<Parameter | undefined>();
  const [isHovered, setIsHovered] = useState(false);

  const handleAddParameter = () => {
    // 确保先清空编辑状态，再打开表单
    setEditingParameter(undefined);
    // 使用 setTimeout 确保状态已经清理完成
    setTimeout(() => {
      setParameterFormVisible(true);
    }, 0);
  };

  const handleEditParameter = (parameter: Parameter) => {
    setEditingParameter(parameter);
    setParameterFormVisible(true);
  };

  const handleParameterFormCancel = () => {
    setParameterFormVisible(false);
    // 延迟清空编辑状态，确保对话框完全关闭后再清理
    setTimeout(() => {
      setEditingParameter(undefined);
    }, 100);
  };

  const handleSetParameterValues = (parameter: Parameter) => {
    setSelectedParameter(parameter);
    setParameterValueFormVisible(true);
  };

  const handleParameterValueFormCancel = () => {
    setParameterValueFormVisible(false);
    setSelectedParameter(undefined);
  };

  const handleParameterValueFormSubmit = async (values: string[]) => {
    if (!selectedParameter) return;
    
    try {
      await onSetParameterValues(category, selectedParameter, values);
      setParameterValueFormVisible(false);
      setSelectedParameter(undefined);
    } catch (error) {
      console.error('Parameter value form submit failed:', error);
      // 重新抛出错误，让 ParameterValueForm 组件处理错误显示
      throw error;
    }
  };

  const handleParameterFormSubmit = async (values: any) => {
    console.log('📝 Parameter form submit:', {
      editingParameter: !!editingParameter,
      category: category.name,
      values: values
    });
    
    try {
      if (editingParameter) {
        console.log('🔄 Updating parameter...');
        await onUpdateParameter(category, editingParameter, values);
      } else {
        console.log('➕ Creating parameter...');
        await onCreateParameter(category, values);
      }
      // 先关闭表单
      setParameterFormVisible(false);
      // 延迟清空编辑状态，确保对话框完全关闭后再清理
      setTimeout(() => {
        setEditingParameter(undefined);
      }, 100);
    } catch (error) {
      console.error('❌ Parameter form submit failed:', error);
      // 重新抛出错误，让 ParameterForm 组件处理错误显示
      throw error;
    }
  };

  const parameters = category.parameters || [];

  const handleCopyCategoryEnglishName = async () => {
    try {
      await navigator.clipboard.writeText(category.name_en);
      message.success('已复制');
    } catch (err) {
      // 降级方案：使用传统方法
      const textArea = document.createElement('textarea');
      textArea.value = category.name_en;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      message.success('已复制');
    }
  };

  return (
    <>
      <div className="category-container">
        <Card
          className="project-card"
          style={{ cursor: 'pointer' }}
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
          onClick={() => setExpanded(!expanded)}
          title={
            <div 
              style={{ 
                display: 'flex', 
                alignItems: 'center', 
                minWidth: 0, 
                width: '100%',
                padding: '4px 0',
                position: 'relative'
              }}
            >
              <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
                <div style={{ 
                  fontSize: '18px', 
                  fontWeight: 700, 
                  overflow: 'hidden', 
                  textOverflow: 'ellipsis', 
                  whiteSpace: 'nowrap',
                  marginBottom: '4px'
                }}>
                  {category.name}
                </div>
                {isHovered && (
                  <Button
                    type="text"
                    size="small"
                    icon={<ArrowUpOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      onPinToTop(category);
                    }}
                    title="置顶"
                    style={{ 
                      position: 'absolute',
                      right: '0',
                      top: '-6px',
                      padding: '4px 8px',
                      color: '#8c8c8c',
                      transition: 'all 0.2s ease',
                      zIndex: 10
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = '#1890ff';
                      e.currentTarget.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = '#8c8c8c';
                      e.currentTarget.style.backgroundColor = 'transparent';
                    }}
                  />
                )}
                <div style={{ 
                  display: 'flex', 
                  justifyContent: 'center',
                  alignItems: 'center'
                }}>
                  <Tag 
                    color="blue" 
                    style={{ 
                      fontSize: '12px',
                      cursor: 'pointer',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '4px',
                      transition: 'all 0.2s ease'
                    }}
                    onClick={(e: React.MouseEvent) => {
                      e.stopPropagation();
                      handleCopyCategoryEnglishName();
                    }}
                    onMouseEnter={(e: React.MouseEvent<HTMLDivElement>) => {
                      e.currentTarget.style.opacity = '0.8';
                    }}
                    onMouseLeave={(e: React.MouseEvent<HTMLDivElement>) => {
                      e.currentTarget.style.opacity = '1';
                    }}
                  >
                    {category.name_en}
                    <CopyOutlined style={{ fontSize: '10px', opacity: 0.6 }} />
                  </Tag>
                </div>
              </div>
            </div>
          }
          actions={[
            <Button
              key="add"
              type="text"
              icon={<PlusOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleAddParameter();
              }}
            >
              添加参数
            </Button>,
            <Button
              key="edit"
              type="text"
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                onEditCategory(category);
              }}
            >
              编辑
            </Button>,
            <Button
              key="delete"
              type="text"
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                onDeleteCategory(category);
              }}
            >
              删除
            </Button>
          ]}
        >
          <div className="project-meta">
            {category.description && (
              <span style={{ color: '#666', fontSize: '14px' }}>
                {category.description}
              </span>
            )}
            <span style={{ color: '#8c8c8c', fontSize: '12px' }}>
              参数数量: {parameters.length} 个
            </span>
          </div>
        </Card>
        
        <div className={`parameter-list-slide-down ${expanded ? 'expanded' : 'collapsed'}`}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin />
            </div>
          ) : parameters.length === 0 ? (
            <Empty
              description="暂无参数"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              style={{ margin: '20px 0' }}
            />
          ) : (
            <div className="parameter-list-container">
              {parameters.map(parameter => (
                <div key={parameter.id} className="parameter-list-item">
                  <ParameterItem
                    parameter={parameter}
                    onEdit={() => handleEditParameter(parameter)}
                    onDelete={() => onDeleteParameter(category, parameter)}
                    onSetValues={() => handleSetParameterValues(parameter)}
                    onPinToTop={() => onPinParameterToTop(category, parameter)}
                  />
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 参数表单 */}
      <ParameterForm
        visible={parameterFormVisible}
        onCancel={handleParameterFormCancel}
        onSubmit={handleParameterFormSubmit}
        initialValues={editingParameter}
        title={editingParameter ? '编辑参数' : '新建参数'}
      />

      {/* 参数值设置表单 */}
      <ParameterValueForm
        visible={parameterValueFormVisible}
        onCancel={handleParameterValueFormCancel}
        onSubmit={handleParameterValueFormSubmit}
        parameter={selectedParameter || null}
        initialValues={selectedParameter?.values || []}
        title={selectedParameter?.values && selectedParameter.values.length > 0 ? "编辑参数值" : "设置参数值"}
        project={project}
      />
    </>
  );
};

export default CategoryCard;
